package m.jclecai.com.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.CountDownTimer;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.klpk.bean.PokerBean;
import m.jclecai.com.bean.klpk.bean.response.IssueInfo;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.fragment.klpk.PokerFragment;
import m.jclecai.com.fragment.klpk.PokerHistoryFragment;
import m.jclecai.com.ui.LotteryHistoryActivity;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.KlpkUtils;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.common.VeticalDrawerLayout;
import m.jclecai.com.view.klpk.KLPKRandomEffect;
import m.jclecai.com.view.klpk.KlpkBarPopupWindow;


/**
 * andy....2017.6.14
 */

public class LotteryKLPKActivity extends BaseActivity implements View.OnClickListener {

    String[] number = {"", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};

    String[] barStr={"对子","同花","顺子","同花顺","豹子","任选一","任选二","任选三","任选四","任选五","任选六"};

    int[] mNumberBgRes = {
            R.drawable.period_spades,
            R.drawable.period_hearts,
            R.drawable.period_plum_blossom,
            R.drawable.period_box};


    @BindView(R.id.tv_period_desc)
    TextView mTvPeriodDesc;

    @BindView(R.id.period_arrow)
    ImageView mPeriodArrow;

/*    @BindView(R.id.ll_period)
    LinearLayout mLlPeriod;*/

    @BindView(R.id.tv_next_period)
    TextView mTvNextPeriod;

    @BindView(R.id.tv_count_down)
    TextView mTvCountDown;

/*    @BindView(R.id.ll_success)
    LinearLayout mLlSuccess;*/
    @BindView(R.id.fl_success)
    RelativeLayout mFlSuccess;

    @BindView(R.id.tv_loading_text)
    TextView mTvLoadingText;

    @BindView(R.id.fl_loading)
    FrameLayout mFlLoading;

    @BindView(R.id.poker_history)
    FrameLayout mPokerHistory;

    @BindView(R.id.poker_container)
    FrameLayout mPokerContainer;

    @BindView(R.id.pullLayout)
    VeticalDrawerLayout mPullLayout;

    @BindView(R.id.tv_betting_number)
    TextView mTvBettingNumber;

    @BindView(R.id.tv_profit)
    TextView mTvProfit;

    @BindView(R.id.ll_bottom_title)
    LinearLayout mLlBottomTitle;

    @BindView(R.id.ll_bottom_view)
    LinearLayout mLlBottomView;

    @BindViews({R.id.iv_period_img1,R.id.iv_period_img2,R.id.iv_period_img3})
    public TextView [] mPokers=new TextView[3];

    PokerFragment mPokerFragment;
    PokerHistoryFragment mPokerHistoryFragment;
    private int mCurrentCategoryIndex;
    private KlpkBarPopupWindow mKlpkBarPopupWindow;
    private PopupWindow mOverFlowPopupWindow;

    private FrameLayout mBottomPokerContainer;
    private LinearLayout mLlPokerContainer;
    private ArrayList<View> mPokerViews;
    private KLPKRandomEffect mKLPKRandomEffect;

    String type="klpk";
    private CountDownTimer mTimer;

    @Override
    protected void initView() {

        setTitle("对子", R.drawable.gs);
        rightOptionText("", R.drawable.action_menu);
        leftOptionText("返回");



       // mLlSuccess.setVisibility(View.INVISIBLE);
        mFlSuccess.setVisibility(View.INVISIBLE);
        mFlLoading.setVisibility(View.VISIBLE);

        //将这里面的业务逻辑抽取到Fragment中去；
        mPokerFragment = new PokerFragment();

        mPokerFragment.setBottomView(mLlBottomView);

        FragmentManager supportFragmentManager = getSupportFragmentManager();
        supportFragmentManager
                .beginTransaction()
                .replace(R.id.poker_container, mPokerFragment)
                .commitAllowingStateLoss();

        mPokerHistoryFragment = new PokerHistoryFragment();
        supportFragmentManager
                .beginTransaction()
                .replace(R.id.poker_history,mPokerHistoryFragment)
                .commitAllowingStateLoss();

        initPopupWindow();

        mBottomPokerContainer = ((FrameLayout) findViewById(R.id.fl_bottom));
        mLlPokerContainer=(LinearLayout)findViewById(R.id.ll_poker_container);

    }

    private void initPopupWindow() {
        //这里的话，有两个PopupWindow一个是mid_title,另一个是右上角的overFlow
        initCenterPopupWindow();
        initOverFlowPopupWindow();
    }

    private void initOverFlowPopupWindow() {
        //这里的话，我们要做的一个操作就是显示右上角的overFlow按钮；
        View view = View.inflate(this, R.layout.klpk_popup_window_overflow, null);

        view.findViewById(R.id.tv_trend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里是走势图的点击事件；
            }
        });

        view.findViewById(R.id.tv_play_desc).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent helpIntent = new Intent(LotteryKLPKActivity.this, WebHelperActivity.class);
                helpIntent.putExtra("title", "玩法介绍");
                helpIntent.putExtra("code", "klpk");
                helpIntent.putExtra("isLocal", true);
                startActivity(helpIntent);
            }
        });

        boolean showMissing = PreferenceUtil.isShowMissing(LotteryKLPKActivity.this);
        final TextView mMissingNumber = (TextView) view.findViewById(R.id.tv_missing);
        //初始化是否显示遗漏
        if (showMissing) {
            //这里我们要做的一个操作就是；
            mMissingNumber.setText("隐藏遗漏");
        }else{
            mMissingNumber.setText("显示遗漏");
        }

        mMissingNumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isShow = PreferenceUtil.isShowMissing(LotteryKLPKActivity.this);
                isShow=!isShow;
                //显示遗漏的事件，这里是保存在sp中的；，如果是显示就变成隐藏，如果是隐藏就是显示；
                if (isShow) {
                    //这里我们要做的一个操作就是；
                    mMissingNumber.setText("隐藏遗漏");
                }else{
                    mMissingNumber.setText("显示遗漏");
                }
                mPokerFragment.showMissingNumber(isShow);
                PreferenceUtil.setIsShowMissing(LotteryKLPKActivity.this,isShow);
                mOverFlowPopupWindow.dismiss();
            }
        });


        view.findViewById(R.id.tv_poker_history).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //历史开奖的事件

                Intent intent = new Intent(LotteryKLPKActivity.this, LotteryHistoryActivity.class);
                intent.putExtra("type", type);
                startActivity(intent);
            }
        });
        view.findViewById(R.id.tv_play_desc).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //玩法介绍的点击事件；

                Intent helpIntent = new Intent(LotteryKLPKActivity.this, WebHelperActivity.class);
                helpIntent.putExtra("title", "玩法介绍");
                helpIntent.putExtra("code", "klpk");
                helpIntent.putExtra("isLocal", true);
                startActivity(helpIntent);
            }
        });

        //这里的话，我们是需要对其View里面的组件进行一个事件监听；
        mOverFlowPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mOverFlowPopupWindow.setFocusable(true);
        mOverFlowPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

       tvRightOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOverFlowPopupWindow.showAsDropDown(tvRightOption);
            }
        });

    }

    private void initCenterPopupWindow() {
        mKlpkBarPopupWindow = new KlpkBarPopupWindow(this);
        mKlpkBarPopupWindow.setPager(mCurrentCategoryIndex);
        mKlpkBarPopupWindow.setOnCategoryChangeListener(new KlpkBarPopupWindow.OnCategoryChangeListener() {
            @Override
            public void OnCategoryChange(int position) {
                //这里我们要做一个操作就是显示
                mPokerFragment.setCurrentPagerIndex(position);
               // tvMidTitle.setText(barStr[position]);
                mCurrentCategoryIndex=position;
            }
        });
    }

    public KLPKRandomEffect getKLPKRandomEffect(){
        return mKLPKRandomEffect;
    }

    @Override
    protected void initData() {


        mPokerViews=new ArrayList<>();

        setCurrentCategoryIndex(0);
        mKlpkBarPopupWindow.setPager(0);
        //这里是机选的一个特效，我们可以将其放在请求网络之后，我们在加载这个布局；
        mKLPKRandomEffect =new KLPKRandomEffect(mBottomPokerContainer,mPokerViews,this);
        initBottomPoker();
       // initCenterPoker(3);

        Typeface typeface = Typeface.createFromAsset(getAssets(), "digital_mono.ttf");
        mTvCountDown.setTypeface(typeface);
        requestDataFromNet();
    }


    /**
     * 这里我们要做的一个事情就是初始化底部的扑克；
     */
    private void initBottomPoker() {

        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();   //得到屏幕的宽度；
        int widthDp = BaseUtils.px2dip(this, width);  //屏幕的宽度dp

        int pokerSize= (widthDp+20)/35+1;   //这里的话，我们可能还要计算牌的高度；

        for (int i = pokerSize; i >=0 ; i--) {
            //这里是我们需要生成poker的数量；
            View view =  View.inflate(this, R.layout.item_bottom_poker, null);

            int rightMargin=i*BaseUtils.dip2px(this,30)-BaseUtils.dip2px(this,15);

            ImageView imageView = (ImageView) view.findViewById(R.id.iv_img);

            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();
            layoutParams.leftMargin=rightMargin;

            imageView.setLayoutParams(layoutParams);

            mBottomPokerContainer.addView(view);
        }
    }



    /**
     * 通过传入poker的数量，来实现对centerPoker的一个初始化；
     */
    public void initCenterPoker(int centerPokerCount) {
        //这里我们要做的一个操作就是显示初始化中间poker();

        mLlPokerContainer.removeAllViews();
        mPokerViews.clear();
        int CENTER_POKER_COUNT=centerPokerCount;

        //动态的生成poker的数量；
        for (int i = 0; i < CENTER_POKER_COUNT; i++) {
            View view= LayoutInflater.from(this).inflate(R.layout.item_center_poker,mLlPokerContainer,false);

            FrameLayout poker = (FrameLayout) view.findViewById(R.id.fl_poker);
            //这里我们
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)poker.getLayoutParams();

            if(i>0){
                layoutParams.leftMargin=-BaseUtils.dip2px(this,81);
            }
            layoutParams.bottomMargin=-BaseUtils.dip2px(this,178);        //让所有的隐藏
            poker.setLayoutParams(layoutParams);

            TextView textView = (TextView) view.findViewById(R.id.tv_poker_text);
            textView.setText(i+"");

            mPokerViews.add(view);
            mLlPokerContainer.addView(view);
        }

    }




    private void requestDataFromNet() {
        HttpManager.getAsyn(Constant_Url.KLPK_ISSUE, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                e.printStackTrace();
                mFlSuccess.setVisibility(View.INVISIBLE);
                mFlLoading.setVisibility(View.VISIBLE);
            }

            @Override
            public void onResponse(String response) {
               // mLlSuccess.setVisibility(View.VISIBLE);
                mFlSuccess.setVisibility(View.VISIBLE);
                mFlLoading.setVisibility(View.INVISIBLE);
                setData(response);
                //成功的话，我们是需要弹出一个对话框的；
                KlpkUtils.showText(LotteryKLPKActivity.this,"期次已更新");
            }
        });
    }


    //@Override
    protected void initListener() {


        mPullLayout.setOnDragStatusChange(new VeticalDrawerLayout.OnDragStatusChange() {
            @Override
            public void onOpen() {

            }

            @Override
            public void onClose() {

            }

            @Override
            public void OnDrag(float percent) {
                //在这里我们将对imageView执行一个动画；
                Float evaluate = evaluate(percent, 0, 180);
                mPeriodArrow.setRotation(evaluate);
            }
        });

        mPeriodArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里的话，我们将打开和关闭这个Click;
                mPullLayout.toggle();
            }
        });

    }


    @OnClick(R.id.tv_mid_title)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_mid_title:
                //这里我们要做的一个操作就是弹出popupWindow
                startAnimation(ivTitleIcon, R.anim.rotate_0_180);
                mKlpkBarPopupWindow.setPager(mCurrentCategoryIndex);
                mKlpkBarPopupWindow.showAsDropDown(rlBar);
                break;
        }
    }


    @Override
    protected int getContentView() {
        return R.layout.activity_lottery_klpk;
    }

    public static Float evaluate(float fraction, Number startValue, Number endValue) {
        float startFloat = startValue.floatValue();
        return startFloat + fraction * (endValue.floatValue() - startFloat);
    }

    //这里我将服务器返回的数据进行一个显示；
    public void setData(String data) {
        //这里的话，我们将数据进行一个解析，将其放到一个
        try {
            Gson gson = new Gson();
            IssueInfo issueInfo = gson.fromJson(data, IssueInfo.class);
            //这里的话我们要做的一个操作就是，显示内容；
            String curPeriod="";
            String prePerod=issueInfo.getData().getPrevIssue().substring(issueInfo.getData().getPrevIssue().length()-2);
            //如果通过上面的判断的话，
            int order = Integer.parseInt(issueInfo.getData().getOrder());
            if (order<10) {
                curPeriod="0"+order;
            }else if(order==10){
                curPeriod=order+"";
            }
            else {
                curPeriod=order+"";
            }

            //这里是多少期：
            mTvNextPeriod.setText("距"+ curPeriod +"期截止");
            //还有多长时间开奖：
            startCountDown(Integer.parseInt(issueInfo.getDeadLine())*1000);

            //上一期是什么情况：这里我们就先认为上一期已经开奖了
            if (!"正,在,开,奖,中".equals(issueInfo.getData().getAwardNumber())) {

                mTvPeriodDesc.setText(prePerod+"期开奖: ");
                List<PokerBean> pokerBeanList = KlpkUtils.getPokerBeanList(issueInfo.getData().getAwardNumber());
                //然后这里我们需要根据PokerBean来显示具体的内容；
                for (int i = 0; i < pokerBeanList.size(); i++) {

                    PokerBean pokerBean = pokerBeanList.get(i);
                    PokerBean.Category category = pokerBean.getCategory();
                    //设置值
                    mPokers[i].setText(number[pokerBean.getNumber()]);
                    if(category== PokerBean.Category.box||category== PokerBean.Category.hearts){
                        mPokers[i].setTextColor(getResources().getColor(R.color.klpk_text_red_color));
                    }else{
                        mPokers[i].setTextColor(Color.BLACK);
                    }
                    //设置背景图片；这里枚举的下标和我们定义的资源文件是一样的，所以这里的话， 我们是可以直接通过枚举的下标来
                    mPokers[i].setBackgroundDrawable(getResources().getDrawable(mNumberBgRes[category.ordinal()]));

                }
            }else{
                //这里表示还是开奖中；
                mTvPeriodDesc.setText(prePerod+"期正在开奖...");
                for (TextView poker : mPokers) {
                    poker.setText("");
                    poker.setBackgroundDrawable(getResources().getDrawable(R.drawable.poker_default));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 这里是，ViewPager里面的Pager会去调用的这个方法，
     * 其作用就是，切换bar上面的的内容，当前选中的值；
     * @param currentCategoryIndex
     */

    public void setCurrentCategoryIndex(int currentCategoryIndex) {
        //这里我们要切换bar上面的内容；
        mCurrentCategoryIndex = currentCategoryIndex;
        //这里的话，我们要做的一个操作就是显示内容；
        tvMidTitle.setText(barStr[mCurrentCategoryIndex]);
    }

    //启动多长时间的定时器
    private void startCountDown(long time) {

        //这里的话， 我们对毫秒进行一个格式化的操作；
        //重新获取信息；
        mTimer = new CountDownTimer(time, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                //这里的话， 我们对毫秒进行一个格式化的操作；

                mTvCountDown.setText(BaseUtils.formatDateLineToString(millisUntilFinished));
            }

            @Override
            public void onFinish() {
                //重新获取信息；
                requestDataFromNet();
                this.cancel();
            }
        };
        mTimer.start();
    }

    @Override
    protected void onDestroy() {
        if (mKLPKRandomEffect != null) {
            mKLPKRandomEffect.resease();
        }
        if (mTimer != null) {
            mTimer.cancel();
        }
        super.onDestroy();
    }
}

